﻿using JinfuyuanProject.Entity;
using JinfuyuanProject.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JinfuyuanProject.Repository
{
    public class RoleRepository : IRoleRepository
    {
        private readonly JinfuyuanDbContext _db;


        public RoleRepository(JinfuyuanDbContext db)
        {
            _db = db;
        }
        #region 基础方法
        public IQueryable<Role> GetList()
        {
            try
            {
                return _db.Role;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        //public IEnumerable<T> QueryBySql<T>(string sql)
        //{
        //    try
        //    {
        //        return _db.Database.SqlQuery<T>(sql);
        //    }
        //    catch (Exception ex)
        //    {
        //        return null;
        //    }
        //    }
        //}
        public bool Delete(Role role)
        {
            try
            {

                _db.Entry(role).State = System.Data.Entity.EntityState.Deleted;
                return _db.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                //记录异常日志
                return false;
            }
        }
        public Role GetModel(int Id)
        {
            try
            {
                Role role = _db.Role.Find(Id);
                return role;
            }
            catch (Exception ex)
            {
                return null;
            }

        }

        public int Insert(Role role)
        {
            try
            {
                _db.Entry(role).State = System.Data.Entity.EntityState.Added;
                _db.SaveChanges();
                return role.Id;
            }
            catch (Exception ex)
            {
                return 0;
            }

        }

        public bool Update(Role role)
        {
            try
            {

                _db.Entry(role).State = System.Data.Entity.EntityState.Modified;
                return _db.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion
        #region 业务方法
        // 获取角色信息
        public async Task<Role> GetRoleByIdAsync(int roleId)
        {
            // 假设角色信息存储在 Role 表中
            return await _db.Role
                .Where(r => r.Id == roleId)
                .FirstOrDefaultAsync();
        }
        #endregion
    }
}
